<?php

	// +----------------------------------------------------------------------
	// | 属性控制器
	// +----------------------------------------------------------------------
	// | Copyright (c) 2015-2024 http://www.yicmf.com, All rights reserved.
	// +----------------------------------------------------------------------
	// | Author: 微尘 <yicmf@qq.com>
	// +----------------------------------------------------------------------

	namespace app\model\cms;

	use think\facade\Config;
	use app\model\admin\Menu;

	class Pattern extends Common
	{

		public $need_pk_list = [
			1 => '是',
			2 => '否',
		];

		public $engine_type_list = [
			'MyISAM' => 'MyISAM',
			'InnoDB' => 'InnoDB',
		];
		public static function onAfterInsert($data)
		{
			$menu = [
				'title' => $data['title'],
				'module' => 'cms',
				'pid' => Menu::where('module', 'cms')->where('title', '门户')->value('id'),
				'controller' => 'admin.Document',
				'action' => 'index?model_name=' . $data['name'],
				'url' => 'admin.Document/index?model_name=' . $data['name'],
				'hide' => 0,
				'tip' => '自动生成模型菜单',
				'icon' => isset($data['icon']) ? $data['icon'] : '',
				'group' => '模型管理'
			];
			Menu::create($menu);
		}
		public static function getModelBuilderGroup($id)
		{
			$model = self::get($id);
			$group = [];
			if ($model && is_array($model->field_group_show)) {
				foreach ($model->field_group_show as $key => $value) {
					dump($model->field_sort[$key]);
					if ($model->extend) {
						$field = Attribute::where('pattern_id', 'in', $model->id . ',' . $model->extend)->where('id', 'in', $model->field_sort[$key])->column('name');

//                    $field = Attribute::where('pattern_id','in',$model->id.','.$model->extend)->order('field(id,'.explode($model->field_sort[$key],',').')')->where('id','in',$model->field_sort[$key])->column('name');
					} else {
						$field = Attribute::where('pattern_id', $model->id)->where('id', 'in', $model->field_sort[$key])->column('name');
					}
					$group[$value] = $field;
				};
			}
			return $group;
		}
		// 通用更新方法
//    public function updateData($data = [])
//    {
//        if (empty($data)) {
//            $this->error = Lang::get('__data_format_error_');
//
//            return false;
//        }
//        // 注册写入后调用事件
//        $this->event('after_write', [$this, 'afterModelWrite']);
//        // 记录行为
//        if (!empty($data['id'])) { // 更新
//            if (!$this->validate()->save($data, ['id' => $data['id']])) {
//                return false;
//            }
//            action_log('model_update', 'model', $data['id'], $this->request->member->id);
//
//            return true;
//        } else { // 新增
//            $result = $this->validate()->save($data);
//            if (!$result) {
//                return false;
//            } else {
//                action_log('model_update', 'model', $this->id, $this->request->member->id);
//
//                return $result;
//            }
//        }
//    }

		// 定义关联模型

		/**
		 * 关联字段定义.
		 */
		public function attribute()
		{
			return $this->hasMany('attribute');
		}
//    /**
//     * 写入后调用事件.
//     */
//    protected function afterModelWrite($data)
//    {
//        // // 清除模型缓存数据
//        Cache::rm('document_model_list');
//    }

		// 获取器
//    public function getAttributeListAttr($value)
//    {
//        return empty($value) ? '' : explode(',', $value);
//    }

//    public function getFieldGroupListAttr($value, $data)
//    {
//        if (0 === strpos($data['field_group'], ':')) {
//            // 采用函数定义
//            return   eval('return '.substr($data['field_group'], 1).';');
//        } elseif (0 === strpos($data['field_group'], '[')) {
//            // 支持读取配置参数（必须是数组类型）
//            return Config::get(substr($data['field_group'], 1, -1));
//        }
//        $array = preg_split('/[,;\r\n]+/', trim($data['field_group'], ",;\r\n"));
//        if (strpos($data['field_group'], ':')) {
//            $result = [];
//            foreach ($array as $val) {
//                list($k, $v) = explode(':', $val);
//                $result[$k]['title'] = $v;
//            }
//        } else {
//            $result = $array;
//        }
//        if (!empty($data['field_sort'])) {
//            $sort = json_decode($data['field_sort'], true);
//            foreach ($result as $key=> $value) {
//                $result[$key]['lists'] = $sort[$key];
//            }
//        }
//
//        return $result;
//    }

		public function getFieldGroupShowAttr($value, $data)
		{
			if (0 === strpos($data['field_group'], ':')) {
				// 采用函数定义
				return eval('return ' . substr($data['field_group'], 1) . ';');
			} elseif (0 === strpos($data['field_group'], '[')) {
				// 支持读取配置参数（必须是数组类型）
				return Config::get(substr($data['field_group'], 1, -1));
			}
			$array = preg_split('/[,;\r\n]+/', trim($data['field_group'], ",;\r\n"));
			if (strpos($data['field_group'], ':')) {
				$result = [];
				foreach ($array as $val) {
					list($k, $v) = explode(':', $val);
					$result[$k] = $v;
				}
			} else {
				$result = $array;
			}
			return $result;
		}

//    public function getFieldSortAttr($value)
//    {
//        return empty($value) ? '' : json_decode($value, true);
//    }


		/**
		 * 写入修改
		 * @param $data
		 */
		public static function onBeforeInsert($data)
		{
			$data['status'] = 1;
			$data['field_group'] = '1:基础';
			$data['name'] =  strtolower($data['name']);
			$data['field_sort'] = empty($data['field_sort']) ? '' : json_encode($data['field_sort']);
			$data['attribute_list'] =  empty($data['attribute_list']) ? '' : implode(',', $data['attribute_list']);
		}



		/**
		 * 获取指定数据库的所有表名.
		 */
		public function getTables()
		{
			return $this->db->getTables();
		}

		/**
		 * 根据数据表生成模型及其属性数据.
		 */
		public function generate($table, $name = '', $title = '')
		{
			// 新增模型数据
			if (empty($name)) {
				$name = $title = substr($table, strlen(Config::get('database.prefix')));
			}
			$data = [
				'name' => $name,
				'title' => $title,
			];
			$data = $this->create($data);
			if ($data) {
				$res = $this->add($data);
				if (!$res) {
					return false;
				}
			} else {
				$this->error = $this->getError();

				return false;
			}

			// 新增属性
			$fields = M()->query('SHOW FULL COLUMNS FROM ' . $table);
			foreach ($fields as $key => $value) {
				$value = array_change_key_case($value);
				// 不新增id字段
				if (strcmp($value['field'], 'id') == 0) {
					continue;
				}

				// 生成属性数据
				$data = [];
				$data['name'] = $value['field'];
				$data['title'] = $value['comment'];
				$data['type'] = 'string'; // TODO:根据字段定义生成合适的数据类型
				// 获取字段定义
				$is_null = strcmp($value['null'], 'NO') == 0 ? ' NOT NULL ' : ' NULL ';
				$data['field'] = $value['type'] . $is_null;
				$data['value'] = $value['default'] == null ? '' : $value['default'];
				$data['pattern_id'] = $res;
				$_POST = $data; // 便于自动验证
				D('Attribute')->update($data, false);
			}

			return $res;
		}

		/**
		 * 删除一个模型.
		 * @param int $id 模型id
		 */
		public function del($id)
		{
			// 获取表名
			$model = $this->field('name,extend')->find($id);
			if ($model['extend'] == 0) {
				$table_name = Config::get('database.prefix') . strtolower($model['name']);
			} elseif ($model['extend'] == 1) {
				$table_name = Config::get('database.prefix') . 'document_' . strtolower($model['name']);
			} else {
				$this->error = '只支持删除文档模型和独立模型';

				return false;
			}

			// 删除属性数据
			M('Attribute')->where([
				'pattern_id' => $id,
			])->delete();
			// 删除模型数据
			$this->delete($id);
			// 删除该表
			$sql = <<<sql
                DROP TABLE {$table_name};
sql;
			$res = M()->execute($sql);

			return $res !== false;
		}
	}
